<template>
    <el-card>

        <template #header>
            <span style="font: 700 22px 微软雅黑;">员工管理</span>
            <div style="float: right;display: flex;gap: 20px;">
                <el-button type="primary" @click="insertFromVisible = true">
                    <el-icon>
                        <Plus />
                    </el-icon>
                    <span>新增员工</span>
                </el-button>
            </div>
        </template>

        <el-table :data="tableData" border height="530" size="large" stripe>
            <el-table-column fixed prop="id" label="ID" width="50" align="center" />
            <el-table-column prop="name" label="姓名" width="150" align="center" />
            <el-table-column prop="gender" label="性别" width="80" align="center" />、
            <el-table-column prop="phone" label="联系电话" width="130" align="center" />
            <el-table-column prop="post" label="职务" width="90" align="center" />

            <el-table-column prop="deptId" label="所属院系ID" width="110" align="center" />
            <el-table-column label="所属院系名称" width="120" align="center">
                <template #default="scope">
                    {{ deptList?.find(obj => scope.row?.deptId === obj?.id)?.name || '' }}
                </template>
            </el-table-column>

            // 时间格式化
            <el-table-column prop="createTime" label="创建时间" width="170" align="center">
                <template #default="scope">
                    {{ new Date(scope.row.createTime).toLocaleString() }}
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="最后一次更新时间" width="170" align="center">
                <template #default="scope">
                    {{ new Date(scope.row.createTime).toLocaleString() }}
                </template>
            </el-table-column>

            <el-table-column fixed="right" label="操作" min-width="10" align="center">
                <template #default="scope">

                    <el-button link type="primary" size="small"
                        @click="updateFromVisible = true; updateFromData = JSON.parse(JSON.stringify(scope.row))">
                        修改
                    </el-button>

                    <el-popconfirm title="不可逆操作，请谨慎执行！" @confirm="deleteSubmit(scope.row.id)">
                        <template #reference>
                            <el-button link type="primary" size="small">删除</el-button>
                        </template>
                    </el-popconfirm>

                </template>
            </el-table-column>
        </el-table>

        <el-row style="margin-top: 25px;">
            <el-col :span="4">
                <el-button type="primary" style="height: 40px;"
                    @click="getData(); getDeptList()">刷新页面</el-button>
            </el-col>
            <el-col :span="19">
                <el-pagination style="justify-content: end" :page-sizes="[5, 10, 20, 50]" background
                    layout="total, sizes, prev, pager, next, jumper," v-model:total="currentTotal"
                    v-model:page-size="currentPageSize" v-model:current-page="currentPage"
                    @size-change="getData()" @current-change="getData()" />
            </el-col>
        </el-row>
    </el-card>

    <!-- 新增弹窗 -->
    <el-dialog v-model="insertFromVisible" title="新增" width="500" style="border-radius: 10px;">

        <el-form ref="insertFromRef" :model="insertFromData" style="margin: 0 auto;width: 350px;"
            :rules="insertFromRules">

            <el-form-item label="员工姓名" prop="name">
                <el-input v-model="insertFromData.name" placeholder="请输入员工姓名" />
            </el-form-item>

            <el-form-item label="员工性别" prop="gender">
                <el-select v-model="insertFromData.gender" placeholder="请选择性别">
                    <el-option label="男" :value="'男'" />
                    <el-option label="女" :value="'女'" />
                </el-select>
            </el-form-item>

            <el-form-item label="联系电话" prop="phone">
                <el-input v-model="insertFromData.phone" placeholder="请输入联系电话" />
            </el-form-item>

            <el-form-item label="员工职务" prop="post">
                <el-input v-model="insertFromData.post" placeholder="请输入职务" />
            </el-form-item>

            <el-form-item label="所属院系" prop="deptId">
                <el-select v-model="insertFromData.deptId" placeholder="请选择院系">
                    <el-option v-for="dept in deptList as any" :label="dept.id + ' : ' + dept.name" :value="dept.id" />
                </el-select>
            </el-form-item>


        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="insertFromVisible = false">关闭</el-button>
                <el-button type="primary" @click="insertSubmit" :loading="insertSubmitLoading">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 修改弹窗 -->
    <el-dialog v-model="updateFromVisible" title="修改" width="500" style="border-radius: 10px;">

        <el-form ref="updateFromRef" :model="updateFromData" style="margin: 0 auto;width: 350px;"
            :rules="updateFromRules">

            <el-tooltip content="主键，不可修改" placement="top">
                <el-form-item label="院系ID" prop="id">
                    <el-input v-model="updateFromData.id" placeholder="请输入院系名ID" disabled />
                </el-form-item>
            </el-tooltip>

            <el-form-item label="员工姓名" prop="name">
                <el-input v-model="updateFromData.name" placeholder="请输入员工姓名" />
            </el-form-item>

            <el-form-item label="员工性别" prop="gender">
                <el-select v-model="updateFromData.gender" placeholder="请选择性别">
                    <el-option label="男" :value="'男'" />
                    <el-option label="女" :value="'女'" />
                </el-select>
            </el-form-item>

            <el-form-item label="联系电话" prop="phone">
                <el-input v-model="updateFromData.phone" placeholder="请输入联系电话" />
            </el-form-item>

            <el-form-item label="员工职务" prop="post">
                <el-input v-model="updateFromData.post" placeholder="请输入职务" />
            </el-form-item>

            <el-form-item label="所属院系" prop="deptId">
                <el-select v-model="updateFromData.deptId" placeholder="请选择院系">
                    <el-option v-for="dept in deptList as any" :label="dept.id + ' : ' + dept.name" :value="dept.id" />
                </el-select>
            </el-form-item>

        </el-form>

        <template #footer>
            <div class="dialog-footer">
                <el-button @click="updateFromVisible = false">关闭</el-button>
                <el-button type="primary" @click="updateSubmit" :loading="updateSubmitLoading">
                    提交
                </el-button>
            </div>
        </template>
    </el-dialog>




</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import axios, { HttpStatusCode } from 'axios';
import { ElMessage } from 'element-plus'

const tableData = ref([])
const deptList = ref([])

onMounted(() => {
    getData()
    getDeptList()
})

async function getData(page = currentPage.value, pageSize = currentPageSize.value) {
    try {
        const result = await axios.get(
            '/api/emp',
            {
                params: {
                    page: page,
                    pageSize: pageSize,
                }
            }
        );
        if (result.data.code === HttpStatusCode.Ok) {
            currentTotal.value = result.data.data.total;
            tableData.value = result.data.data.rows;
        } else {
            ElMessage({
                message: '获取数据失败！！！',
                type: 'error',
            })
        }
    } catch (err) {
        console.log(err);
    }
}

async function getDeptList() {
    try {
        const result = await axios.get('/api/dept/list');
        if (result.data.code === HttpStatusCode.Ok) {
            deptList.value = result.data.data;
        } else {
            ElMessage({
                message: '获取数据失败！！！',
                type: 'error',
            })
        }
    } catch (err) {
        console.log(err);
    }
}


// 分页，相关属性，函数 
const currentTotal = ref(100);
const currentPage = ref(1);
const currentPageSize = ref(10);



// 新增弹窗，相关属性函数 ----------------------------------------------------------------
const insertFromRef = ref() // 表单实例（新增）
const insertFromVisible = ref(false) // 弹窗显示开关（新增）
const insertSubmitLoading = ref(false) // 提交加载状态开关（新增）
// 表单数据（新增）
const insertFromData = ref({
    name: '',
    gender: '男',
    phone: '',
    post: '',
    deptId: null,
})
// 表单验证规则（新增）
const insertFromRules = {
    name: [
        { required: true, message: '必填项不应该为空', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '必填项不应该为空', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '必填项不应该为空', trigger: 'blur' },
        { patten: /^1[34578]\d{9}$/, min: 11, max: 11, message: '请输入正确的手机号', trigger: 'change' }
    ],
    post: [
        { required: true, message: '必填项不应该为空', trigger: 'blur' }
    ],
    deptId: [
        { required: true, message: '必填项不应该为空', trigger: 'blur' }
    ],
}



// 修改弹窗，相关属性函数 ----------------------------------------------------------------
const updateFromRef = ref() // 表单实例（修改）
const updateFromVisible = ref(false) // 弹窗显示开关（修改）
const updateSubmitLoading = ref(false) // 提交加载状态开关（修改）
// 表单数据（修改）
const updateFromData = ref({
    id: '',
    ...insertFromData.value,
})
// 表单验证规则（修改）
const updateFromRules = {
    ...insertFromRules,
}



// 接口访问 -----------------------------------------------------------------------------
// 新增
async function insertSubmit() {
    try {
        insertSubmitLoading.value = true;

        // 验证表单
        const validate = await insertFromRef.value.validate(e => e)
        if (!validate) {
            ElMessage({ message: '请检查表单', type: 'warning' })
            return
        }

        const data = {
            name: insertFromData.value.name,
            gender: insertFromData.value.gender,
            phone: insertFromData.value.phone,
            post: insertFromData.value.post,
            deptId: insertFromData.value.deptId,
        }
        const result = await axios.post('/api/emp', data)
        if (result.data.code === HttpStatusCode.Ok) {
            getData()
            insertFromVisible.value = false
        }
    } catch (err) {
        console.log(err);

        ElMessage({
            message: '提交失败！！！',
            type: 'error',
        })
    } finally {
        insertSubmitLoading.value = false
    }
}
// 修改
async function updateSubmit() {
    try {
        updateSubmitLoading.value = true;

        // 验证表单
        const validate = await updateFromRef.value.validate(e => e)
        if (!validate) {
            ElMessage({ message: '请检查表单', type: 'warning' })
            return
        }

        const data = {
            id: updateFromData.value.id,
            name: updateFromData.value.name,
            gender: updateFromData.value.gender,
            phone: updateFromData.value.phone,
            post: updateFromData.value.post,
            deptId: updateFromData.value.deptId,
        }
        const result = await axios.put('/api/emp', data)
        if (result.data.code === HttpStatusCode.Ok) {
            getData()
        }
    } catch (err) {
        console.log(err);

        ElMessage({
            message: '提交失败！！！',
            type: 'error',
        })
    } finally {
        updateFromVisible.value = false
        updateSubmitLoading.value = false
    }
}
// 删除
async function deleteSubmit(id: number) {
    try {
        const arr = []
        arr.push(id)

        const result = await axios.delete('/api/emp/' + arr)
        if (result.data.code === HttpStatusCode.Ok) {
            getData()
        }
    } catch (error) {
        console.log(error)
        ElMessage({
            message: '访问接口失败！！！',
            type: 'error',
        })
    }
}



// 查询，相关属性函数
// const search = ref('');

</script>